<?php

namespace app\api\controller\ec;

use app\common\controller\Api;
use app\common\exception\UploadException;
use think\Config;
use think\Hook;
use think\Db;

/**
 * 公共接口
 * 第一步:先添加客户 到ec
 * 第二步:根据客户手机号 获取CrmId
 * 第三步：根据CrmId 获取客户信息
 */
class Ecautotuisongfeiyu extends Ecbase {

    public function _initialize() {
        parent::_initialize();
    }
    
    
    /***
     * 飞鱼客户入库
     */
    
    public function tuisongFeiyuKehu(){
       
        while (true){           
//            $today_start_time = strtotime("today");           
//            if((time() > $today_start_time + 18 * 3600) || (time() < $today_start_time + 8 * 3600)){
//                usleep(5000000);
//                continue;
//            }
//            sleep(5);
                        
            $status = db('ec_zhongzhuan_config')->where('name','feiyu_to_ec_status')->value('value');
            if(empty($status)){
                sleep(5);
                echo date('Y-m-d H:i:s') . "\r\n";
                continue;
            }
            sleep(5);
            $list = db('ec_assign_feiyu_kehu')->where('status','<>',2)->order('createtime desc')->limit(1)->select();
            



            foreach ($list as $key=>$value){

                if(empty($value['auto_assign']))                continue;
                //$status 0 暂停   1 分配中  2 分配完成
//                $assing_kehu_detail = db('ec_assign_feiyu_kehu_detail')->field('SUM(people - success_people) daifenpei')->where('people','>',0)->where('assign_id',$value['id'])->where('assign_status',1)->find();
           
                
                $kehu_list = array();
//                $daifenpei = empty($assing_kehu_detail['daifenpei']) ? 0 : $assing_kehu_detail['daifenpei'];
                
                
//                if(empty($daifenpei)) continue;
                
                //每天的分配计划
                $assign_detail_success_data = db('ec_assign_feiyu_kehu_detail')->alias('a')
                        ->join('ec_user u','a.user_id = u.id')
                        ->where('a.people','>',0)
//                        ->where('u.is_shangban',1)
                        ->where('a.assign_id',$value['id'])
//                        ->where('a.assign_status',1)
                        ->order('a.people desc,u.id asc')
                        ->column('a.user_id,a.success_people,a.people,u.kehu_count,u.is_shangban,0 end_assign_time,0 assign_people');
                

//                $limit = $daifenpei > 500 ? 500 :$daifenpei;
                $limit = 10;
             

                $kehu_list= db('ec_feiyu_xiansuo')->field('id byid,clue_id,telphone customerTelephone,name customerName,clue_create_time startTime,memo')->where([
                    'status'=>0,
                    'is_enable_assign'=>1
                ])->limit($limit)->order('clue_create_time asc')->select();
                
                if(empty($kehu_list) || empty($assign_detail_success_data)) continue;
                
                $starttime = strtotime('today');
                $endtime = $starttime + 86400;
                $today_assign_list = db('ec_assign_feiyu_kehu_detail_log')->where([
                    'createtime'=>['between',[$starttime,$endtime]]
                ])->order('end_assign_time desc')->column('user_id,assign_people,end_assign_time');

                foreach ($today_assign_list as $to_key =>$to_value){
                    if(empty($assign_detail_success_data[$to_key])) continue;
                    $assign_detail_success_data[$to_key]['assign_people'] = $to_value['assign_people'];
                    $assign_detail_success_data[$to_key]['end_assign_time'] = $to_value['end_assign_time'];
                }
                qqq('tuisongFeiyuKehu1',$assign_detail_success_data);
                

                
                $insert_data = [];
                $task_phone_update = [];                
                $success_assign_count = 0;
                
               
                foreach ($kehu_list as $kehu_info){                    
                    $controller = '\app\common\controller\zhongzhuan\Autoassignfeiyu';
                    $result = call_user_func_array(array($controller, 'getAssingUserId'),array(['list'=>$assign_detail_success_data]));    
                    $assign_detail_success_data = $result['list'];
                    $user_id = $result['user_id'];
                    qqq('tuisongFeiyuKehu2',$user_id);
                    qqq('tuisongFeiyuKehu3',$assign_detail_success_data);
                    if(empty($user_id)){                        
                        break;
                    } 
                   
                    
                    $param = ['assign_id'=>$value['id'],'kehu_info'=>$kehu_info,'user_id'=>$user_id];
                    $assign_data = call_user_func_array(array($controller, 'startAssign'),array($param));    
                    if(!empty($assign_data)){
                        $success_assign_count =  $success_assign_count  + 1;
                        $task_phone_update[] = $assign_data['byid'];
                        $insert_data[] = $assign_data;
                        
                        list($msec, $sec) = explode(' ', microtime());
                        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
                        
                        $assign_detail_success_data[$user_id]['success_people']=  $assign_detail_success_data[$user_id]['success_people'] + 1;
                        $assign_detail_success_data[$user_id]['assign_people']=  $assign_detail_success_data[$user_id]['assign_people'] + 1;
                        $assign_detail_success_data[$user_id]['kehu_count'] = $assign_detail_success_data[$user_id]['kehu_count'] + 1;
                        $assign_detail_success_data[$user_id]['end_assign_time'] = $msectime;                       
                        
                        
                    }
                   

                }
                qqq('tuisongFeiyuKehu4',$assign_detail_success_data);
                
                try{
                    Db::startTrans();
                    $starttime = strtotime('today');
                    $endtime = $starttime + 86400;
                    foreach ($assign_detail_success_data as $us_key=>$us_value){  
                        $save_data = [];
                        $save_data['success_people'] = $us_value['success_people'];
//                        if($us_value['success_people'] >= $us_value['people']){
//                            $save_data['assign_status'] = 2;
//                        }
                        $today_info = db('ec_assign_feiyu_kehu_detail_log')->field('assign_people,id')->where([
                            'user_id'=>$us_key,
                            'createtime'=>['between',[$starttime,$endtime]]
                        ])->find();
                        if(empty($today_info)){
                            db('ec_assign_feiyu_kehu_detail_log')->insertGetId([
                                'user_id'=>$us_key,'createtime'=>time(),'end_assign_time'=>$us_value['end_assign_time'],
                                'assign_people'=>$us_value['assign_people']
                            ]);
                        }else{
                            db('ec_assign_feiyu_kehu_detail_log')->where('id',$today_info['id'])->update([
                                'end_assign_time'=>$us_value['end_assign_time'],
                                'assign_people'=>$us_value['assign_people'],
                            ]);
                        }
                        
                        
                        
                        db('ec_assign_feiyu_kehu_detail')->where(['user_id'=>$us_key,'assign_id'=>$value['id']])->update($save_data);
                        db('ec_user')->where(['id'=>$us_key])->update(['kehu_count'=>$us_value['kehu_count']]);
                    }

                    db('ec_aiuser_to_ecuser_feiyu')->insertAll($insert_data);
                    db('ec_feiyu_xiansuo')->where('id','in',$task_phone_update)->setField('status',1);
                    
//                    $daituisong_count  = $value['daituisong_count'] + $success_assign_count;
//                    
//
//                    if($daituisong_count >= $value['count']){             
//                        db('ec_assign_feiyu_kehu')->where('id',$value['id'])->update(['daituisong_count'=>$daituisong_count,'status'=>2]);
//                    }else{
//                         db('ec_assign_feiyu_kehu')->where('id',$value['id'])->update(['daituisong_count'=>$daituisong_count,'status'=>1]);
//                    }
                    
                    Db::commit();
                }catch(\Exception $e){        
                    var_dump($e->getMessage());
                    Db::rollback();
                }
                
                

            }         
            
        
            
        }
        
               
    }
        



    /** 
     * 推送客户 
     */
    public function addCustomer(){
        while (true){
            
            $status = db('ec_zhongzhuan_config')->where('name','feiyu_to_ec_status')->value('value');
            if(empty($status)){
                sleep(5);
                echo date('Y-m-d H:i:s') . "\r\n";
                continue;
            }
            
            
            $list = db('ec_aiuser_to_ecuser_feiyu')->limit(50)->order('id asc')->where(['status'=>0])->select();
        
            if(empty($list)){
                sleep(5);
                continue;
            }
            $end_list =  [];
            $org_kehu_list = [];
            foreach ($list as $value){
                $content = json_decode($value['content'],true);
                $end_list[] = $content;
                $org_kehu_list[] = [
                    'id'=>$value['id'],
                    'mobile'=>$value['mobile']
                ];
            }
            $param = [
                'kehu_list' => $end_list,
                'opt_userid'=>$this->optUserId,
                'org_kehu_list'=>$org_kehu_list,
            ] ;

            $controller = '\app\common\controller\zhongzhuan\Fenpeifeiyu';
            $data = call_user_func_array(array($controller, 'addCustomer'), array($param));
//            qqq('addCustomer1',$data);
            
//            usleep() 函数延迟执行当前脚本若干微秒（一微秒等于一百万分之一秒）。 延迟5秒
//            usleep(5000000);
        }
        
        
        
        
    }
    
    
    /**
     * 更新客户标签  while  最大 200
     */
    public function ownUpdateKehuLabel(){
        
        while (true){
            $status = db('ec_zhongzhuan_config')->where('name','feiyu_to_ec_status')->value('value');
            if(empty($status)){
                sleep(5);
                echo date('Y-m-d H:i:s') . "\r\n";
                continue;
            }
            

            $label_config = [
                config('feiyu.xinzeng_feiyu_label'), //客户来源 【新增飞鱼】
            ];

            $list = db('ec_aiuser_to_ecuser_feiyu')->where(['status'=>1,'label_laiyuan_biaoji_status'=>0,'ecid'=>['>',0]])->where('crmId','<>','')->limit(200)->select();
            
            if(empty($list)){
                sleep(5);
                continue;
            }
            
            
            $end_list = $item_kehu_ids = $crmIds = [];
            foreach ($list as $value){
                $crmIds[] = $value['crmId'];
                $item_kehu_ids[] = $value['id'];
            }
            
            $param = ['crmIds' => implode(',', $crmIds),'optUserId'=>$this->optUserId,'labels'=>implode(',', $label_config)] ;
            $controller = '\app\common\controller\zhongzhuan\Fenpeifeiyu';
            $item_response = call_user_func_array(array($controller, 'updateKehuLabel'), array($param));

            if($item_response['code'] == 200){
                db('ec_aiuser_to_ecuser_feiyu')->where('id','in',$item_kehu_ids)->setField('label_laiyuan_biaoji_status',1);
            }

            
            // usleep() 函数延迟执行当前脚本若干微秒（一微秒等于一百万分之一秒）。 延迟5秒
            usleep(5000000);
        }
        
    }
    
    
    /**
     * 批量变更跟进人 最大50
     */
    public function batchUpdateKehuOwner(){
        while(true){
            
            $status = db('ec_zhongzhuan_config')->where('name','feiyu_to_ec_status')->value('value');
            if(empty($status)){
                sleep(5);
                echo date('Y-m-d H:i:s') . "\r\n";
                continue;
            }
            
            $list = db('ec_aiuser_to_ecuser_feiyu')->where(['status'=>2,'ecid'=>['>',0]])->limit(50)->select();
            
            if(empty($list)){
                sleep(30);
                continue;
            }

            foreach ($list as $key=>$value){
                $item_crmId = $value['crmId'];
                $item_mobile = $value['mobile'];
                $controller = '\app\common\controller\zhongzhuan\Fenpeifeiyu';
                $msg_prefix = '[变更跟进人]';

                $save_data = [];
                if(empty($item_crmId)){
                    $item_crmId = db('ec_kehu')->where(['mobile'=>$item_mobile])->whereNotNull('crmId')->order('id desc')->value('crmId');                    
                }
                
                if(empty($item_crmId)) continue;


//                if(empty($item_crmId)){
//                    $param = ['mobile' => $item_mobile] ;
//                    $item_response = call_user_func_array(array($controller, 'getKehuInfoByOptUserid'), array($param));
//                    if($item_response['code'] == 200){
//                        $item_data = $item_response['data']['list'][0];
//                        $item_crmId = $item_data['crmId'];
//                    }
//                }

                if(empty($item_crmId)){
                    $save_data['tuisong_result_txt'] = $msg_prefix .  'CrmID不存在';
                }else{
                    $save_data['crmId'] = $item_crmId;
                    $content = json_decode($value['content'],true);
                    if(!empty($content['followUserId'])){
                        $param_owner = ['followUserId'=>$content['followUserId'],'crmIds'=>$item_crmId,'optUserId'=>$this->optUserId];
                        $item_update_owner = call_user_func_array(array($controller, 'updateKehuOwnwer'), array($param_owner));

                        if($item_update_owner['code'] == 200){
                            foreach ($item_update_owner['data']['list'] as $k=>$v){
                                if($v['code'] == 40003 || $v['code'] == 200){
                                    $save_data['status'] = 1;
                                }
                                $save_data['tuisong_result_txt'] = $msg_prefix . $v['msg'];
                            }

                        }else{
                            $save_data['tuisong_result_txt'] = $msg_prefix . '请求失败';
                        }
                    }else{
                        $save_data['tuisong_result_txt'] = $msg_prefix . '跟进人为空';
                    }


                }      


                db('ec_aiuser_to_ecuser_feiyu')->where('id',$value['id'])->update($save_data);

            }
            
            

           
           usleep(5000000);
        }
         
    }
    

    
    /**
     * 批量获取crmid
     */
    public function batchGetKeHhCrmByMobile(){
        while(true){
            
            $status = db('ec_zhongzhuan_config')->where('name','feiyu_to_ec_status')->value('value');
            if(empty($status)){
                sleep(5);
                echo date('Y-m-d H:i:s') . "\r\n";
                continue;
            }
            
            
            $list = db('ec_aiuser_to_ecuser_feiyu')->limit(50)->where('status',2)->where('crmId','')->select();
            if(empty($list)){
                sleep(30);
            }
            $mobile = [];
            foreach ($list as $key=>$value){
                $info = db('ec_kehu')->field('crmId,mobile')
                        ->whereNotNull('crmId')
                        ->where('mobile',$value['mobile'])->order('id desc')->find();
                if(!empty($info)){
                    db('ec_aiuser_to_ecuser_feiyu')->where('id',$value['id'])->setField('crmId',$info['crmId']);
                }else{
                    $mobile[] = $value['mobile'];
                }
                
            }
            
            
            if(empty($mobile)) continue;
            

           $param = ['mobile' => implode(',', $mobile)] ;
           qqq('batchGetKeHhCrmByMobile',$mobile);
           $controller = '\app\common\controller\zhongzhuan\Fenpeifeiyu';
           $item_response = call_user_func_array(array($controller, 'getKehuInfoByOptUserid'), array($param));          
           qqq('batchGetKeHhCrmByMobile',$item_response);
           if($item_response['code'] == 200){
               $insert_data = [];
               
               foreach ($item_response['data']['list'] as $value){
                   $middle_data = [];
                   $item_mobile = $value['mobiles'][0];
                   $item_crmId = $value['crmId'];       
                   if(empty($item_mobile)) continue;
                   
                   db('ec_aiuser_to_ecuser_feiyu')->where(['mobile'=>$item_mobile,'crmId'=>''])->setField('crmId',$item_crmId);
                   $count = db('ec_kehu')->where(['mobile'=>$item_mobile])->count();
                   if(!empty($count)){
                       db('ec_kehu')->where(['mobile'=>$item_mobile])->setField('crmId',$item_crmId);
                   }else{
                       $middle_data['follow_userid'] = empty($value['followUserId'])? 0 : $value['followUserId']; 
                        $middle_data['mobile'] = $item_mobile;                
                        $middle_data['crmId'] =$item_crmId;
                        $middle_data['name'] = $value['name'];
                        $middle_data['content'] = json_encode($value,JSON_UNESCAPED_UNICODE);
                        $middle_data['createtime'] = time();
                        $insert_data[] = $middle_data;                        
                   }
                   
                   
               }
               if(!empty($insert_data)){
                   db('ec_kehu')->insertAll($insert_data);
               }
           }
           
        }
         
    }
    
    
    
    /**
    * 批量添加跟进记录
    */
    public function batchSaveUserTrajectory(){
        while(true){
            
            
                      
            
            $kehu_list = db('ec_aiuser_to_ecuser_feiyu')->limit(200)->order('id asc')->where(['genjin_status'=>0])->select();
            
            if(empty($kehu_list)){
                sleep(30);
            }
            $list = [];
            foreach ($kehu_list as $value){
                if(empty($value['crmId']))                    continue;
                
                
                $feiyu_kehu_info = db('ec_feiyu_xiansuo')->field('content')->where('clue_id',$value['callJobId'])->find();

                if(empty($feiyu_kehu_info))  continue;
                
                $feiyu_kehu_info_org = json_decode($feiyu_kehu_info['content'],true);
                $memo = '';
                foreach ($feiyu_kehu_info_org['remark_dict'] as $k => $v){
                    $memo .= $k .':' .$v;
                }
                
                $temp_str = '联系人姓名:' . $feiyu_kehu_info_org['name'] . "\r\n";
                $temp_str .= '手机号:'. $feiyu_kehu_info_org['telphone'] . "\r\n";
                $temp_str .= '来源:巨量引擎广告'.  "\r\n";
                $temp_str .= '备注:'. $memo . "\r\n";
                $temp_str .= '地区:'. $feiyu_kehu_info_org['location'] . "\r\n";
                $temp_str .= '所属广告账号:'. $feiyu_kehu_info_org['adv_name'] . "\r\n";
                $temp_str .= '广告计划:'. $feiyu_kehu_info_org['promotion_name'] . "\r\n";
                $temp_str .= '站点名称:'. $feiyu_kehu_info_org['site_name'] . "\r\n";
                $temp_str .= '推广落地页:'. $feiyu_kehu_info_org['external_url'] . "\r\n";
                

                $list[] = [
                    "id"=>$value['id'],"crmId"=>$value['crmId'],"userId"=>$this->optUserId,"content"=>$temp_str
                ];


            }       
            
            
            if(empty($list)) continue;

            $controller = '\app\common\controller\zhongzhuan\Fenpeifeiyu';
            $response_data = call_user_func_array(array($controller, 'saveUserTrajectory'), array(['list'=>$list]));
            
            if($response_data['code'] == 200){
                $update_data_id = [];
                foreach ($response_data['data'] as $value){
                    if($value['errCode'] == 200){
                        $update_data_id[] = $value['id'];
                    }
                    
                    
                }
                
                
                if(!empty($update_data_id)){
                    $temp = [];
                    $temp['genjin_status'] = 1;
//                    $temp['updatetime'] = time();
                    db('ec_aiuser_to_ecuser_feiyu')->where("id",'in',$update_data_id)->update($temp);
                }
            }
            
            
        }
        
        
    }
    
   
    
  
}
